package com.yj.auto.component.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.Constants;
import com.yj.auto.component.base.model.Msg;
import com.yj.auto.component.base.model.MsgBox;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.web.system.model.User;
import com.yj.auto.helper.AutoHelper;

/**
 * Msg 管理 描述：
 */
@Service(name = "msgSrv")
public class MsgService extends BaseService<Msg> {

	private static final Log logger = Log.getLog(MsgService.class);

	public static final String SQL_LIST = "component.msg.list";
	public static final String ATTA_MSG = "msg_atta";
	public static final String ACTION_DRAFT = "draft";
	public static final String ACTION_SENT = "sent";
	public static final Msg dao = new Msg().dao();

	@Override
	public Msg getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("ctime desc");
		}
		return getSqlPara(SQL_LIST, query);
	}

	public boolean save(Msg model) {
		Integer[][] attas = getAttas(model, ATTA_MSG);
		if (attas != null && attas[0] != null && attas[0].length > 0) {
			model.setAtta("1");// 是否有附件
		}
		boolean success = super.save(model);
		if (success) {
			saveBox(model);
		}
		return success;
	}

	public boolean update(Msg model) {
		boolean success = super.update(model);
		if (success) {
			deleteBox(model.getId());
			saveBox(model);
		}
		return success;
	}

	// 删除邮件主表，不能直接调用
	public boolean delete(Integer... ids) {
		if (null == ids || ids.length < 1)
			return false;
		boolean success = true;
		for (Integer id : ids) {
			deleteById(id, ATTA_MSG);
		}
		return success;
	}

	private void saveBox(Msg model) {
		Integer id = model.getId();// 消息主键
		Integer from = model.getFromId();// 发件人ID
		// deleteBox(from, MsgBox.BOX_TYPE_DRAFT, id);// 先删除草稿箱中的记录
		if (MsgService.ACTION_DRAFT.equals(model.get("action"))) {// 只保存草稿
			this.saveBox(id, from, MsgBox.BOX_TYPE_DRAFT, model.getCtime());
			return;
		}
		// 发件箱
		this.saveBox(id, from, MsgBox.BOX_TYPE_OUTBOX, model.getCtime());

		// 接收者
		String to = model.getToId();
		String cc = model.getCcId();
		if (null == to && cc == null)
			return;
		if (null != cc && cc.length() > 1) {
			to = to + ";" + cc;
		}
		String[] ss = to.split(";");
		List<Integer> userIds = new ArrayList<Integer>();
		String folderType = MsgBox.BOX_TYPE_INBOX;
		for (String idStr : ss) {
			if (idStr.length() < 2)
				continue;
			if (idStr.startsWith("U")) {// U=用户
				Integer uid = Integer.parseInt(idStr.substring(1));
				if (!userIds.contains(uid)) {
					userIds.add(uid);
					this.saveBox(id, uid, folderType, null);
				}
			} else if (idStr.startsWith("O")) {// O=组织机构，把此机构下的所有人员查询出来
				List<User> list = AutoHelper.getUserService().findByOrg(Integer.parseInt(idStr.substring(1)), Constants.DATA_STATE_VALID);
				for (User u : list) {
					if (!userIds.contains(u.getId())) {
						userIds.add(u.getId());
						this.saveBox(id, u.getId(), folderType, null);
					}
				}
			}
		}
	}

	private void saveBox(Integer msgId, Integer userId, String boxType, Date readTime) {
		MsgBox model = new MsgBox();
		model.setMsgId(msgId);
		model.setUserId(userId);
		model.setType(boxType);
		model.setReadTime(readTime);
		model.save();
	}

	private boolean deleteBox(Integer msgId) {
		String sql = "delete from t_com_msg_box where msg_id=? ";
		boolean success = Db.update(sql, msgId) > 0;
		return success;
	}

	public boolean deleteBox(Integer userId, String boxType, Integer... ids) {
		if (null == ids || ids.length < 1 || userId == null || StrKit.isBlank(boxType))
			return false;
		boolean success = true;
		for (Integer msgId : ids) {
			String sql = "delete from t_com_msg_box where msg_id=? and user_id=? and type=?";
			boolean temp = Db.update(sql, msgId, userId, boxType) > 0;
			if (temp) {
				if (isInvalid(msgId)) {// 无效消息, 删除消息主表
					delete(msgId);
				}
			}
			success = success && temp;
		}
		return success;
	}

	// 无效消息，文件夹中没有任何引用
	public boolean isInvalid(Integer id) {
		String sql = "select count(1) from t_com_msg_box where msg_id=? ";
		boolean success = Db.queryLong(sql, id) < 1;
		return success;
	}

	// 收件箱中的未读邮件数量
	public Long getUnreadInboxCount(Integer userId) {
		String sql = "select count(1) from t_com_msg_box where read_time is null and user_id=? ";
		long count = Db.queryLong(sql, userId);
		return count;
	}

	// 更新邮件的首次阅读时间
	public boolean updateUserReadTime(Integer msgId, Integer userId) {
		String sql = "update t_com_msg_box set read_time=? where msg_id=? and user_id=?";
		boolean success = Db.update(sql, Constants.NOW(), msgId, userId) > 0;
		return success;
	}
}